import asyncio
import re
import traceback

from bot.insurance_planner_gpt.agent.script.premium_calculation import PremiumCalculation
from bot.insurance_planner_gpt.user_info import UserInfo
from common.log import logger
from knowledge_base.knowledge_embedding import BGEQuery
import pandas as pd
import os
import itertools
from collections import defaultdict
from langchain.schema import Document
from knowledge_base.document_search import get_products_name, get_products_introduction
from bot.insurance_planner_gpt.utils.user_info_util import CandidateProducts
from bot.insurance_planner_gpt.utils.standard_terms_util import StandardTerms
from bot.insurance_planner_gpt.agent.insurance_underwriting import InsuranceUnderwriting


class CausalDataProcessUtil:
    # 加载知识库
    knowledge_base_query = BGEQuery()
    knowledge_base_query.load_all_knowledge_base()
    # 获取保险产品配置
    # products_config_df = pd.read_csv('../doc/products_config.csv', encoding='utf-8')
    current_script_path = os.path.abspath(__file__)
    csv_file_path = os.path.normpath(os.path.join(current_script_path, '../../doc/products_config.csv'))
    products_config_df = pd.read_csv(csv_file_path, encoding='utf-8')
    products_config_df.fillna('', inplace=True)
    products_config_df = products_config_df.set_index('产品名称')
    products_config = products_config_df.to_dict(orient='index')
    products_name = get_products_name(
        os.path.normpath(os.path.join(current_script_path, "../../doc/products_name.txt")))
    products_introduction = get_products_introduction(
        os.path.normpath(os.path.join(current_script_path, "../../doc/products_introduction.txt")))
    embeddings = knowledge_base_query.embeddings
    candidate_product = CandidateProducts(embeddings=embeddings, products_name=products_name,
                                          products_config=products_config)
    question_answer_file = os.path.normpath(os.path.join(current_script_path, "../../doc/用户问题-答疑解惑.xlsx"))
    standard_terms = StandardTerms(question_answer_file)
    insurance_underwriting = InsuranceUnderwriting()

    def __init__(self):
        pass

    # async def process_data_from_causal(self, causal_list_str):
    #     """处理从因果图里解析的数据"""
    #     process_result = {}
    #     try:
    #         # 区分类型
    #         if '（保险产品名称）' in causal_list_str:
    #             process_result['类型'] = '保险产品'
    #         elif '（保险产品类型）' in causal_list_str:
    #             process_result['类型'] = '保险产品类型'
    #         elif '（保险类型）' in causal_list_str:
    #             process_result['类型'] = '保险类型'
    #
    #         solution_plan_causal_list = causal_list_str.split('\n')
    #         user_need_info_list = []
    #         if '类型' in process_result and process_result['类型'] == '保险产品':
    #             await self.process_insurance_product(solution_plan_causal_list, user_need_info_list)
    #         elif '类型' in process_result and process_result['类型'] == '保险产品类型':
    #             await self.process_insurance_product_type(solution_plan_causal_list, user_need_info_list)
    #         elif '类型' in process_result and process_result['类型'] == '保险类型':
    #             await self.process_insurance_type(solution_plan_causal_list, user_need_info_list)
    #         if user_need_info_list:
    #             process_result['产品方案'] = user_need_info_list
    #     except:
    #         logger.error(traceback.format_exc())
    #     return process_result

    async def process_data_from_communication_strategy(self, need_calculate_list):
        """处理从因果图里解析的数据"""
        process_result_list = []
        need_calculate_list = [
            # '铁甲小保2号少儿长期医疗险 ->长期医疗险-> 慧择铁甲小保2号少儿长期医疗险（保险产品名称）（保险类型：医疗险，保险产品类型：百万医疗险）-> 可以报销特需病房、私立医院的费用（条款说明）（需讲解）',
            # '特需病房 ->长期医疗险-> 慧择铁甲小保2号少儿长期医疗险（保险产品名称）（保险类型：医疗险，保险产品类型：百万医疗险）-> 可以报销特需病房、私立医院的费用（条款说明）（需讲解）',
            # '小青龙少儿重疾险->重疾险-> 小青龙少儿重疾险（保险产品名称）（保险类型：重疾险，保险产品类型：重疾险）-> 重大疾病保障金赔付（条款说明）（需讲解）',
            # '身故全残保障金->重疾险-> 小青龙少儿重疾险（保险产品名称）（保险类型：重疾险，保险产品类型：重疾险）-> 重大疾病保障金赔付（条款说明）（需讲解）',
            # '意外险-> 小蜜蜂3好意外险（保险产品名称）（保险类型：意外险，保险产品类型：意外险）-> 意外伤害赔付保障金（条款说明）（需讲解）',
            '需要医疗险-> 医疗险（保险类型）-> 意外伤害赔付保障金（条款说明）（需讲解）',
            '需要医疗险-> 医疗险（保险类型）-> 意外伤害赔付保障金（条款说明）（需讲解）',
            '需要百万医疗险-> 百万医疗险（保险产品类型）-> 意外伤害赔付保障金（条款说明）（需讲解）',
            '大病治疗-> 百万医疗险（保险产品类型）-> 意外伤害赔付保障金（条款说明）（需讲解）',
        ]
        try:
            if need_calculate_list:
                for need_calculate in need_calculate_list:
                    process_result = {}
                    # 区分类型
                    if '（保险产品名称）' in need_calculate:
                        process_result['类型'] = '保险产品'
                    elif '（保险产品类型）' in need_calculate:
                        process_result['类型'] = '保险产品类型'
                    elif '（保险类型）' in need_calculate:
                        process_result['类型'] = '保险类型'
                    result = {}
                    if '类型' in process_result and process_result['类型'] == '保险产品':
                        result = await self.process_insurance_product(need_calculate)
                    elif '类型' in process_result and process_result['类型'] == '保险产品类型':
                        result = await self.process_insurance_product_type(need_calculate)
                    elif '类型' in process_result and process_result['类型'] == '保险类型':
                        result = await self.process_insurance_type(need_calculate)
                    if result:
                        process_result['产品方案'] = result
                        process_result["计算目标"] = ["计算保额", "计算保费"]
                        process_result_list.append(process_result)

                # 创建一个字典，用于存储已经见过的产品和他们的需求
                merged_data = {}

                # 遍历原始数据
                for item in process_result_list:
                    key = (item.get('类型', ''), item.get('产品方案', {}).get('名称', ''))
                    if key not in merged_data:
                        merged_data[key] = {
                            '类型': item.get('类型', ''),
                            '产品方案': item.get('产品方案', {}),
                            '计算目标': item.get('计算目标', []),
                        }
                    else:
                        # 如果已经存在该键值对，则合并产品需求
                        merged_data.setdefault(key, {}).setdefault('产品方案', {}).setdefault('产品需求', {}).update(
                            item.get('产品方案', {}).get('产品需求', {})
                        )

                # 将字典转换为最终的JSON对象列表
                process_result_list = list(merged_data.values())
        except:
            logger.error(f"处理沟通策略异常，处理内容是：{need_calculate_list}，异常是:{traceback.format_exc()}")
        return process_result_list

    async def process_insurance_product_type(self, solution_plan_causal):
        """处理保险产品类型相关"""
        process_result = {}
        try:
            solution_plan_causal = solution_plan_causal.replace("(", "（") \
                .replace(")", "）").replace("-> ", "->").replace(" ->", "->").replace(":", "：")
            idx_1 = solution_plan_causal.rfind('（保险产品类型）')
            idx_0_0 = solution_plan_causal.rfind('->', 0, idx_1)
            if idx_0_0 > 1 and idx_1 > idx_0_0 + 2:
                product_type = solution_plan_causal[idx_0_0 + 2:idx_1]
                if product_type:
                    need_new = True
                    # 判断保险产品是不是已经存在了
                    if product_type == process_result.get('保险产品类型', ''):
                        need_new = False
                    if need_new:
                        process_result = {
                            "名称": product_type,
                        }
        except Exception:
            logger.error(f"处理保险产品类型相关，内容是：{solution_plan_causal}，异常{traceback.format_exc()}")
        return process_result

    async def process_insurance_type(self, solution_plan_causal):
        """处理保险类型相关"""
        process_result = {}
        try:
            solution_plan_causal = solution_plan_causal.replace("(", "（") \
                .replace(")", "）").replace("-> ", "->").replace(" ->", "->").replace(":", "：")
            # 正则表达式模式 截取保险产品名称
            idx_1 = solution_plan_causal.rfind('（保险类型）')
            idx_0_0 = solution_plan_causal.rfind('->', 0, idx_1)
            if idx_0_0 > 1 and idx_1 > idx_0_0 + 2:
                insurance_type = solution_plan_causal[idx_0_0 + 2:idx_1]
                if insurance_type:
                    need_new = True
                    # 判断保险产品是不是已经存在了
                    if insurance_type == process_result.get('名称', ''):
                        need_new = False
                    if need_new:
                        process_result = {
                            "名称": insurance_type,
                        }
        except Exception:
            logger.error(f"处理保险类型相关异常,处理内容是：{solution_plan_causal}，异常为：{traceback.format_exc()}")
        return process_result

    async def process_insurance_product(self, need_calculate):
        """从因果图处理保险产品相关"""
        process_result = {}
        try:
            if "保险产品" in need_calculate:
                insurance_product_type, insurance_type = await self.get_insurance_type(need_calculate)
                need_new = True
                # 从因果图里提取用户的需求项 搜索向量库
                results = await self.format_and_search_product(need_calculate)
                if results:
                    result = results[0]
                    if '产品属性' in result.metadata:
                        items_val_str = result.metadata.get('属性值', '')
                        item_str = result.metadata.get('产品属性', '')
                        product_name = result.metadata.get('保险产品', '')
                        requirements = {}
                        if process_result:
                            # 判断保险产品是不是已经存在了
                            if product_name == process_result.get('名称', ''):
                                requirements = process_result.get('产品需求', {})
                                need_new = False
                        # 给产品属性一个默认值
                        if items_val_str:
                            items_val_list = items_val_str.split('/')
                            item = ""
                            if len(items_val_list) > 1:
                                item = items_val_list[1]
                            elif len(items_val_list) == 1:
                                item = items_val_list[0]
                            requirements[item_str] = item
                        if need_new:
                            process_result = {
                                "名称": product_name,
                                "保险类型": insurance_type,
                                "保险产品类型": insurance_product_type,
                                "产品需求": requirements
                            }
        except Exception:
            logger.error(f"从因果图处理保险产品，异常：{traceback.format_exc()}")
        return process_result

    async def get_insurance_type(self, solution_plan_causal):
        insurance_type = ""
        insurance_product_type = ""
        try:
            # 编写正则表达式
            get_type_pattern = r'（保险类型：(.*?)，保险产品类型：(.*?)）'
            # 使用re.search查找匹配项
            match_type = re.search(get_type_pattern, solution_plan_causal)
            if match_type:
                insurance_type = match_type.group(1)  # 提取保险类型
                insurance_product_type = match_type.group(2)  # 提取保险产品类型
        except:
            logger.error(f"从因果图处理保险产品，提取保险产品类型异常：{traceback.format_exc()}")
        return insurance_product_type, insurance_type

    async def format_and_search_product(self, need_calculate):
        """格式化产品 搜索向量库"""
        product_item_results = None
        try:
            solution_plan_causal = need_calculate.replace("(", "（") \
                .replace(")", "）").replace("-> ", "->").replace(" ->", "->").replace(":", "：")
            # 正则表达式模式 截取保险产品名称
            idx_1 = solution_plan_causal.rfind('（保险产品名称）')
            idx_0_0 = solution_plan_causal.rfind('->', 0, idx_1)
            if idx_0_0 > 1 and idx_1 > idx_0_0 + 2:
                product_name = solution_plan_causal[idx_0_0 + 2:idx_1]
                if product_name:
                    if '->' in solution_plan_causal:
                        item_list = solution_plan_causal.split('->')
                        if item_list:
                            need_item = item_list[0]
                            # 构建查询条件查询向量库
                            if '保险规划_' in need_item:
                                need_item = need_item.replace("保险规划_", "")
                            # search_str = "保险产品:" + product_name + "\n" + "产品属性:" + need_item.replace(" ", "")
                            # knowledge_results = self.knowledge_base_query.search_product_item_with_score(search_str,
                            #                                                                              top_k=1,
                            #                                                                              limit_score=0.3)
                            # if knowledge_results:
                            #     product_item_results = [item for item in knowledge_results if '产品属性' in item.metadata]
                            # else:
                            search_str = "保险产品:" + product_name + "\n" + "产品属性:" + "无"
                            knowledge_results = self.knowledge_base_query.search_product_item_with_score(search_str,
                                                                                                         top_k=1,
                                                                                                         limit_score=0.4)
                            product_item_results = [item for item in knowledge_results if '产品属性' in item.metadata]
        except Exception:
            logger.error(f"格式化产品异常:{traceback.format_exc()}")
        return product_item_results

    async def gen_explain_background_knowledge(self, user_question, insurance_result):
        """ 获取解释方案背景知识 """
        background_knowledge = []
        try:
            product_details = insurance_result.get('产品方案', [])
            explain_type = insurance_result.get('类型', '')

            # 通用知识默认加入到知识库
            # common_knowledge_results = self.knowledge_base_query.search_insurance_knowledge(query=user_question,
            #                                                                                 product_name_input="保险知识",
            #                                                                                 top_k=6)
            # if common_knowledge_results:
            #     for search_result in common_knowledge_results:
            #         background_knowledge.append(search_result)

            # 保险产品讲解增加到知识库
            if '保险产品' == explain_type and product_details:
                product_explain = []
                for product_detail in product_details:
                    product_name = product_detail.get("名称")
                    search_results = self.knowledge_base_query.search_insurance_knowledge(query=user_question,
                                                                                          product_name_input=product_name,
                                                                                          top_k=8)
                    if search_results:
                        for search_result in search_results:
                            background_knowledge.append(search_result)

                background_knowledge.extend(product_explain)
            elif '保险产品类型' == explain_type and product_details:
                product_type_explain = []
                for product_detail in product_details:
                    product_type_name = product_detail.get('名称', '')
                background_knowledge.extend(product_type_explain)
            elif '保险类型' == explain_type and product_details:
                insurance_type_explain = []
                for product_detail in product_details:
                    insurance_type_name = product_detail.get('名称', '')
                background_knowledge.extend(insurance_type_explain)

        except Exception:
            logger.error(f"获取解释方案背景知识异常{traceback.format_exc()}")
        return background_knowledge

    async def gen_explain_background_knowledge_new(self, user_question, user_info):
        """ 获取解释方案背景知识 """
        background_knowledge = []
        try:
            if "当前关注保险产品" in user_info:
                product_names = user_info["当前关注保险产品"].strip().split(',')
            else:
                product_names = ["保险知识"]
            user_questions = [q for q in user_question.strip().split('\n') if "（当下关注）" in q]
            question_product = list(itertools.product(user_questions, product_names))
            query_set = set()
            for question, product_name in question_product:
                question = question.replace("（当下关注）", "").replace("保险规划_", "")
                search_results = self.knowledge_base_query.search_insurance_knowledge(query=question,
                                                                                      product_name_input=product_name,
                                                                                      top_k=5)
                if search_results:
                    for search_result in search_results:
                        if search_result[1] not in query_set:
                            background_knowledge.append(search_result)
                            query_set.add(search_result[1])
            background_knowledge = sorted(background_knowledge, key=lambda x: x[0])
            background_knowledge = [m[1] for m in background_knowledge[:5]]

        except Exception:
            logger.error(f"获取解释方案背景知识异常{traceback.format_exc()}")
        return background_knowledge

    def get_product_name(self, solution_plan_causal):
        """获取产品名称"""
        product_name = ''
        try:
            product_pattern = re.compile(r'->(.+?)（保险产品名称）')
            product_match = re.search(product_pattern, solution_plan_causal)
            if product_match:
                product_name = product_match.group(1)
        except Exception:
            logger.error(f"获取产品名称异常{traceback.format_exc()}")
        return product_name

    async def match_solution_info(self, user_info, insurance_person_info, raw_solutions, top_k=1, stage3_topk=None):
        """根据用户情境，找到每个阶段最匹配的方案"""
        result = []
        try:
            for stage, stage_solutions in raw_solutions.items():
                if stage == '阶段三':
                    # 核查阶段三产品方案可用性，不可用的加上说明
                    modify_solutions = []
                    for solution in stage_solutions:
                        product_name = self.get_product_name(solution['问题解决方案'])
                        if_available, unavailable_reason = await self.insurance_underwriting.check_product_available(
                            product_name,
                            insurance_person_info)
                        if not if_available:
                            # 如果该产品无效则加上无效说明
                            solution['问题解决方案'] = '无效方案：' + solution['问题解决方案'] + '（' + unavailable_reason + '）'
                            modify_solutions.append(solution)
                            logger.info(f"【核保模块】：产品{product_name}不可用，原因：{unavailable_reason}")
                # 找到最匹配的top方案
                tmp_solution = []
                for solution in stage_solutions:
                    user_stage = solution.get('用户情境', '')
                    if user_stage:
                        user_stage_processed = user_stage.split(',')
                        user_stage_dict = {item.split(":")[0]: item.split(":")[1] for item in user_stage_processed}
                        match_stage_score = self.user_info_match_score(user_info, user_stage_dict)
                    else:
                        match_stage_score = 0.5  # 没有用户情境的默认0.5分,即这种作为兜底方案
                    if not solution['问题解决方案'].startswith('无效方案'):
                        # match_stage_score = match_stage_score - 100  # 无效方案减100分，这样即使用户问的就是不在库内的，也一样能给出top匹配的方案
                        # 无效方案则不出现，只保留有效方案
                        solution['匹配度'] = match_stage_score
                        tmp_solution.append(solution)
                # 按照匹配度排序,取top方案
                tmp_solution = sorted(tmp_solution, key=lambda x: x['匹配度'], reverse=True)
                print('--- tmp_solution方案和匹配度：---', tmp_solution)
                solution_values = [item['问题解决方案'] for item in tmp_solution if '问题解决方案' in item]
                if stage3_topk and stage == '阶段三':
                    the_top_k = stage3_topk
                else:
                    the_top_k = top_k
                result = result + solution_values[:the_top_k]
        except Exception:
            logger.error(f"情境匹配方案异常{traceback.format_exc()}")
        return result

    def user_info_match_score(self, user_info, user_stage_dict):
        """计算用户情境和用户信息的匹配度"""
        try:
            intersection = {k: user_info[k] for k in user_info if user_stage_dict.get(k) == user_info[k]}
            result = len(intersection)
        except Exception:
            logger.error(f"计算用户情境和用户信息的匹配度异常{traceback.format_exc()}")
        # TODO 不一致的要扣分，一致的要加分，包括一些取值里 或 范围 的情况需要匹配
        return result

    async def gen_explain_background_knowledge_by_strategy(self, plan_explain_list):
        """ 获取解释方案背景知识 """
        background_knowledge = []
        question_product = []
        try:
            for explain in plan_explain_list:
                explain = explain.replace(' ', '').strip()
                user_question = ""
                product_name = ""
                standard_question = ""
                idx_0 = explain.find('->')
                if idx_0 > 1:
                    user_question = explain[:idx_0]
                idx_1 = explain.rfind('（保险产品名称）')
                idx_0_0 = explain.rfind('->', 0, idx_1)
                if idx_0_0 > 1 and idx_1 > idx_0_0 + 2:
                    product_name_input = explain[idx_0_0 + 2:idx_1]
                    # product_name = match_product_name(self.products_name, product_name_input)
                    product_name = self.candidate_product.get_sim_product(product_name_input)
                idx_2 = explain.rfind('->')
                idx_3 = explain.rfind('（需讲解）')
                if idx_2 > 1 and idx_3 > idx_2 + 2:
                    standard_question = explain[idx_2 + 2:idx_3]
                    if '（保险产品名称）' in standard_question:
                        standard_question = ""
                if product_name and standard_question:
                    question_product.append((standard_question, product_name))
                if product_name and user_question:
                    question_product.append((user_question, product_name))
                if not product_name and user_question:
                    question_product.append((user_question, ""))

            if len(question_product) == 0:
                return background_knowledge
            query_set = set()
            for question, product_name in question_product:
                question = question.replace("（当下关注）", "").replace("保险规划_", "")
                search_results = self.knowledge_base_query.search_insurance_knowledge(query=question,
                                                                                      product_name=product_name,
                                                                                      products_introduction={},
                                                                                      top_k=12)
                terms_content = self.standard_terms.get_terms_by_question(question, product_name)
                if terms_content != "":
                    search_results.append((0.015, terms_content))
                if search_results:
                    for search_result in search_results:
                        if search_result[1] not in query_set:
                            background_knowledge.append(search_result)
                            query_set.add(search_result[1])
                    # # 把产品链接和投保方式增加到背景知识中
                    # product_config = self.products_config.get(product_name, '')
                    # add_product_config = '\n保险产品:'+product_name
                    # if product_config:
                    #     if product_config['是否在售']==1:
                    #         if product_config['产品链接']:
                    #             add_product_config = add_product_config+ '\n产品链接：' + product_config['产品链接'] + '\n投保方式：' + product_config['投保方式']
                    #     else:
                    #         add_product_config = add_product_config + '\n 该产品已下架'
                    # add_product_config = (0.001,add_product_config)
                    # if add_product_config[1] not in query_set:
                    #     background_knowledge.append(add_product_config)
                    #     query_set.add(add_product_config[1])
            background_knowledge = sorted(background_knowledge, key=lambda x: x[0])
            background_knowledge = [m[1] for m in background_knowledge[:20]]
            background_knowledge = '\n\n'.join(background_knowledge)

        except Exception:
            logger.error(f"获取解释方案背景知识异常{traceback.format_exc()}")

        return background_knowledge

    async def get_base_product_info_by_strategy(self, product_info_list):
        """ 获取产品简介、链接（是否在售），作为基础背景知识 """
        base_product_info = []
        try:
            # 拿到所有产品名（去重）
            product_name_set = set()
            for explain in product_info_list:
                explain = explain.replace(' ', '').strip()
                product_name = ""
                # idx_0 = explain.find('->')
                idx_1 = explain.rfind('（保险产品名称）')
                idx_0_0 = explain.rfind('->', 0, idx_1)
                if idx_0_0 > 1 and idx_1 > idx_0_0 + 2:
                    product_name_input = explain[idx_0_0 + 2:idx_1]
                    # product_name = match_product_name(self.products_name, product_name_input)
                    product_name = self.candidate_product.get_sim_product(product_name_input)
                if product_name:
                    product_name_set.add(product_name)
            if len(product_name_set) == 0:
                return ''
            for product_name in product_name_set:
                # 1）产品链接和投保方式
                product_config = self.products_config.get(product_name, '')
                add_product_config = ''
                if product_config:
                    add_product_config = add_product_config + '\n保险产品:' + product_name
                    if product_config['是否在售'] == 1:
                        if product_config['产品链接']:
                            add_product_config = add_product_config + '\n产品链接：' + product_config[
                                '产品链接'] + '\n投保方式：' + product_config['投保方式']
                    else:
                        add_product_config = add_product_config + '\n 该产品已下架'
                # 2）产品简介
                product_introduction = self.products_introduction.get(product_name, '')
                if product_introduction:
                    add_product_config = add_product_config + '\n产品简介：' + product_introduction
                base_product_info.append(add_product_config)
            base_product_info = '\n\n'.join(base_product_info)
        except Exception:
            logger.error(f"获取产品基础知识异常{traceback.format_exc()}")
        return base_product_info


    async def get_company_knowledge_by_user_question(self, question_list):
        """ 根据用户问题检索到回复话术 """
        company_knowledge = []
        try:
            for question in question_list:
                search_results = self.knowledge_base_query.search_company_knowledge(query=question,
                                                                                    type='用户问题',
                                                                                    top_k=3,
                                                                                    limit_score=2)
                company_knowledge = company_knowledge + search_results
            company_knowledge = '\n'.join(company_knowledge)
        except Exception:
            logger.error(f"获取公司知识-用户问题话术异常{traceback.format_exc()}")
        return company_knowledge

    async def get_company_knowledge_by_strategy(self, strategy_list_use):
        """ 根据用沟通策略检索到的回复话术 """
        company_knowledge = []
        # strategy_list_use = [
        #     '重疾险->重疾险（保险类型）->询问被保人和年龄（需用户提供）',
        #     '重疾险相关信息->重疾险（保险类型）（需讲解）',
        #     '测试->x->y->m（效果）'
        # ]
        strategy_list_result = []
        for strategy in strategy_list_use:
            # 分割字符串，获取倒数第二个元素
            parts = strategy.split("->")
            second_to_last = parts[-2]
            # 使用正则表达式寻找最后的（xxx）形式
            match = re.search(r'（[^）]*）$', parts[-1])
            if match:
                # 如果匹配到（xxx）的形式，最后一个元素就是上一个
                strategy_list_result.append(second_to_last)
            else:
                # 否则，最后一个元素直接作为结果
                strategy_list_result.append(parts[-1])
        try:
            for question in strategy_list_result:
                search_results = self.knowledge_base_query.search_company_knowledge(query=question,
                                                                                    type='沟通策略',
                                                                                    top_k=3,
                                                                                    limit_score=2)
                company_knowledge = company_knowledge + search_results
            company_knowledge = '\n'.join(company_knowledge)
        except Exception:
            logger.error(f"获取公司知识-沟通策略话术异常{traceback.format_exc()}")
        return company_knowledge



if __name__ == '__main__':
    # import re

    # data = '保险规划_铁甲小保2号少儿长期的保费计算（当下关注）->x->慧择铁甲小保2号少儿长期医疗险（保险产品名称）（保险类型：医疗险，保险产品类型：百万医疗险）'
    #
    # # 编写正则表达式
    # pattern = r'->.*?->(.*?)（保险产品名称）（保险类型：(.*?)，保险产品类型：(.*?)）'
    #
    # # 使用re.search查找匹配项
    # match = re.search(pattern, data)
    #
    # if match:
    #     insurance_name = match.group(1)  # 提取保险类型
    #     insurance_type = match.group(2)  # 提取保险类型
    #     insurance_product_type = match.group(3)  # 提取保险产品类型
    #     print(f"保险产品: {insurance_name}")
    #     print(f"保险类型: {insurance_type}")
    #     print(f"保险产品类型: {insurance_product_type}")
    # else:
    #     print("没有找到匹配项")
    # import time
    # s1 = time.time()
    util = CausalDataProcessUtil()
    # background_knowledge = asyncio.run(util.gen_explain_background_knowledge_by_strategy(["保险规划_百万医疗保险的保险范围->百万医疗（保险产品类型）->长相安长期医疗险（20年保证续保）（保险产品名称）（保险类型：医疗险，保险产品类型：百万医疗险）->投保规则（需讲解）"]))
    # print(background_knowledge)
    # print(time.time() - s1)

    need_cal_list = asyncio.run(util.process_data_from_communication_strategy(''))
    user_info = {}
    user_info_en = UserInfo.get_english_dict(user_info)
    premium_calculation = PremiumCalculation(user_info_en)
    insurance_coverage_cal_result_list = asyncio.run(premium_calculation.calculate_insurance_coverage(
        need_cal_list))
    cal_result_str = asyncio.run(premium_calculation.transfer_product2str(insurance_coverage_cal_result_list))
    print(cal_result_str)
